package com.chenenjun.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.chenenjun.dao.IUserDAO;
import com.chenenjun.dao.UserDAOImpl;
import com.chenenjun.vo.BBSUser;

public class UserServiceImpl implements IUserService {
	
	private IUserDAO dao = new UserDAOImpl();
	
	private static Map<String,String> types=new HashMap<String,String>();
	/** 初始化上传文件的临时存放目录 */  
	private static File tmpDir = null;  
	/** 初始化上传文件后的保存目录 */  
	private static File saveDir = null;  
	
	static{
		//{"image/jpeg","image/gif","image/x-ms-bmp","image/png"};
		types.put("image/jpeg", ".jpg");
		types.put("image/gif", ".gif");
		types.put("image/x-ms-bmp", ".bmp");
		types.put("image/png", ".png");
		
		String tmpDirPath = "" + System.getProperty("file.separator") + "tmpDir";
		String saveDirPath = "" + System.getProperty("file.sparator") + "saveDir";
		
		tmpDir = new File(tmpDirPath);
		saveDir = new File(saveDirPath);
		
		if(!tmpDir.exists()){
			tmpDir.mkdir();
		}
		
		if(!saveDir.exists()){
			saveDir.mkdir();
		}
	}
	
	@Override
	public BBSUser login(BBSUser user) {
		// TODO Auto-generated method stub
		return dao.login(user);
	}

	@Override
	public boolean register(BBSUser user) {
		// TODO Auto-generated method stub
		return dao.register(user);
	}

	@Override
	public BBSUser upload(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String path = request.getServletContext().getRealPath("/");
/*		System.out.println(path);
 * 		输出结果：
 * 		F:\apache-tomcat-8.0.33-windows-x64\apache-tomcat-8.0.33\wtpwebapps\BBS\
 *		是tomcat路径加上项目名 
*/
		BBSUser user = new BBSUser();
		try {
			request.setCharacterEncoding("utf-8");
			//判断文件上传类型是不是enctype="multipart/form-data"
			if(ServletFileUpload.isMultipartContent(request)){
				// 创建一个基于磁盘的项目
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setRepository(tmpDir);// 指定上传文件的临时目录
				factory.setSizeThreshold(1024*1024*100);// 指定内存中缓存数据的大小，单位为byte
				// 创建一个新的文件上传处理程序
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setFileSizeMax(1024*1024*10);// 指定单个上传文件的最大尺寸
				upload.setSizeMax(1024*1024*50);// 指定一次请求上传多个文件的总尺寸 
				FileItemIterator iterator = upload.getItemIterator(request);
				while(iterator.hasNext()){
					FileItemStream fileItemStream = iterator.next();
					String contentType = fileItemStream.getContentType();
					String fieldName = fileItemStream.getFieldName();
					InputStream is = fileItemStream.openStream();
					if(!fileItemStream.isFormField() &&
							fileItemStream.getName().length() > 0){// 判断是否是文件域（即不是form表单里的），并且已经选择头像了
						if(types.get(contentType) == null){
							request.setAttribute("information", "头像类型不匹配");
							break;
						}
						BufferedInputStream bis = new BufferedInputStream(is);
						String fileName = path + "upload\\" + UUID.randomUUID() + types.get(contentType);
						BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
						Streams.copy(bis, bos, true);
						user.setPicPath(fileName);
						System.out.println(fileName);
						bis.close();
						bos.flush();
						bos.close();
					} else {
						switch (fieldName) {
						case "reusername":
							user.setUsername(Streams.asString(is, "utf-8"));
							break;
						case "repassword":
							user.setPassword(Streams.asString(is, "utf-8"));
							break;
						default:
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public byte[] queryPicById(int id) {
		// TODO Auto-generated method stub
		return dao.queryPicById(id);
	}

	@Override
	public boolean chancePAGENUM(int PAGENUM, int id) {
		// TODO Auto-generated method stub
		return dao.chancePAGENUM(PAGENUM, id);
	}

}
